import { Singleton } from './singleton';
import { Logger } from './logger';

/** 事件处理函数类型 */
type EventHandler = (...args: any[]) => void;

/**
 * 事件管理器
 */
@Singleton
export class EventManager {
    /** 事件映射表 */
    private eventMap: Map<string, Set<EventHandler>> = new Map();
    
    /** 日志管理器 */
    private logger: Logger = new Logger();

    /**
     * 注册事件监听器
     * @param event 事件名称
     * @param handler 事件处理函数
     */
    on(event: string, handler: EventHandler): void {
        if (!this.eventMap.has(event)) {
            this.eventMap.set(event, new Set());
        }
        this.eventMap.get(event)?.add(handler);
        this.logger.debug(`[EventManager] Registered handler for event: ${event}`);
    }

    /**
     * 注销事件监听器
     * @param event 事件名称
     * @param handler 事件处理函数
     */
    off(event: string, handler: EventHandler): void {
        const handlers = this.eventMap.get(event);
        if (handlers) {
            handlers.delete(handler);
            if (handlers.size === 0) {
                this.eventMap.delete(event);
            }
            this.logger.debug(`[EventManager] Unregistered handler for event: ${event}`);
        }
    }

    /**
     * 触发事件
     * @param event 事件名称
     * @param args 事件参数
     */
    emit(event: string, ...args: any[]): void {
        const handlers = this.eventMap.get(event);
        if (handlers) {
            handlers.forEach(handler => {
                try {
                    handler(...args);
                } catch (error) {
                    this.logger.error(`[EventManager] Error in event handler for ${event}:`, error);
                }
            });
            this.logger.debug(`[EventManager] Emitted event: ${event}`);
        }
    }

    /**
     * 注册一次性事件监听器
     * @param event 事件名称
     * @param handler 事件处理函数
     */
    once(event: string, handler: EventHandler): void {
        const onceHandler = (...args: any[]) => {
            this.off(event, onceHandler);
            handler(...args);
        };
        this.on(event, onceHandler);
        this.logger.debug(`[EventManager] Registered one-time handler for event: ${event}`);
    }

    /**
     * 清除指定事件的所有监听器
     * @param event 事件名称
     */
    clear(event: string): void {
        this.eventMap.delete(event);
        this.logger.debug(`[EventManager] Cleared all handlers for event: ${event}`);
    }

    /**
     * 清除所有事件监听器
     */
    clearAll(): void {
        this.eventMap.clear();
        this.logger.debug('[EventManager] Cleared all event handlers');
    }
} 